using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using GameOverlayWPF.Services;

namespace GameOverlayWPF
{
    public partial class MainWindow : Window
    {
        private bool _isAutoHideEnabled = false;
        private bool _isMouseOverWindow = false;
        private const int HOTKEY_ID = 9000;
        private const int AUDIO_HOTKEY_ID = 9001;
        private HotkeySettings _hotkeySettings;
        private DatabaseManager dbManager;
        private ObservableCollection<Scheme> schemes;
        private bool _isAobMode = false; // false=烽火地带, true=全面战场
        private string? _currentSortBy = null; // null=默认, "hot"=热门, "latest"=最新
        private DispatcherTimer? _topmostTimer; // 定期检查窗口置顶的定时器
        private IntPtr _keyboardHookHandle = IntPtr.Zero; // 低级键盘钩子句柄
        private bool _isLoading = false; // 是否正在加载数据
        private System.Diagnostics.Stopwatch _loadTimer = new System.Diagnostics.Stopwatch(); // 性能监控
        
        // 分页加载相关
        private const int PAGE_SIZE = 30; // 每页显示30个方案
        private int _currentPage = 1;
        private bool _hasMoreData = true;
        private List<object> _allItems = new List<object>(); // 存储所有已加载的数据
        private System.Threading.CancellationTokenSource? _loadCancellationToken; // 用于取消加载
        private readonly HashSet<int> _copyingSchemeIds = new HashSet<int>(); // 跟踪正在复制的方案ID
        private IntPtr _previousForegroundWindow = IntPtr.Zero; // 保存显示覆盖层前的前台窗口（游戏窗口）

        public MainWindow()
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("MainWindow constructor started");
                InitializeComponent();
                System.Diagnostics.Debug.WriteLine("InitializeComponent completed");
                
                // 添加调试输出
                System.Diagnostics.Debug.WriteLine("MainWindow constructor called");
                
                // 初始化标题，显示热键提示
                UpdateWindowTitleWithHotkey();
                
                InitializeWindowBehavior();
                System.Diagnostics.Debug.WriteLine("InitializeWindowBehavior completed");
                
                SetupEventHandlers();
                System.Diagnostics.Debug.WriteLine("SetupEventHandlers completed");
                
                // 初始化数据库管理器和方案集合
                dbManager = DatabaseManager.Instance;
                schemes = new ObservableCollection<Scheme>();
                SchemesList.ItemsSource = schemes;
                System.Diagnostics.Debug.WriteLine("Database manager initialized");
                
                // 加载热键设置
                _hotkeySettings = HotkeySettings.Instance;
                System.Diagnostics.Debug.WriteLine($"[MainWindow] 热键设置已加载: {_hotkeySettings.HotkeyText}");
                System.Diagnostics.Debug.WriteLine($"[MainWindow] 配置文件中的透明度: {_hotkeySettings.WindowOpacity}");
                
                // 应用窗口透明度设置
                this.Opacity = _hotkeySettings.WindowOpacity;
                System.Diagnostics.Debug.WriteLine($"[MainWindow] 窗口透明度已应用: {this.Opacity} ({_hotkeySettings.WindowOpacity * 100}%)");
                
                // 初始化动画配置 - 极致优雅的企业级配置
                InitializeAnimationConfiguration();
                System.Diagnostics.Debug.WriteLine("企业级动画配置已初始化");
                
                // 注意：已移除图片刷新定时器，图片通过数据绑定自动更新，不需要刷新整个列表
                
                InitializePriceFilter();
                System.Diagnostics.Debug.WriteLine("Price filter initialized");
                
                // 初始化武器筛选器状态
                InitializeWeaponFilter();
                System.Diagnostics.Debug.WriteLine("Weapon filter initialized");
                
                // 设置默认排序为热门方案
                _currentSortBy = "hot";
                // 延迟更新按钮状态，确保按钮已初始化
                this.Loaded += (s, e) => UpdateSortButtonStates();
                
                // 延迟加载数据，确保窗口先显示，避免阻塞UI
                this.Loaded += (s, e) =>
                {
                    // 使用Dispatcher延迟执行，让窗口先完全显示
                    Dispatcher.BeginInvoke(new Action(async () =>
                    {
                        try
                        {
                            await Task.Delay(100); // 短暂延迟，确保窗口已显示
                            LoadMapPasswordsAsync(); // 加载今日密码
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine($"加载地图密码失败（非致命）: {ex.Message}");
                        }
                        
                        try
                        {
                            _ = LoadCategoriesAsync(); // 异步加载，不等待
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine($"加载分类失败（非致命）: {ex.Message}");
                        }
                        
                        // 不在初始化时加载武器，等用户选择武器类型后再加载
                        // 确保具体武器筛选器保持禁用状态
                        
                        try
                        {
                            _ = LoadSchemesAsync(); // 异步加载，不等待
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine($"加载方案失败（非致命）: {ex.Message}");
                        }
                    }), DispatcherPriority.Background);
                };
                
                // 窗口加载后再注册热键
                this.Loaded += MainWindow_Loaded;
                
                // 确保窗口始终在顶层
                this.Activated += MainWindow_Activated;
                this.Deactivated += MainWindow_Deactivated;
                
                // 添加窗口关闭事件处理，清理资源
                this.Closed += MainWindow_Closed;
                
                // 加载用户信息
                LoadUserInfo();
                
                // 初始化音频服务 - 启用麦克风输出功能
                InitializeAudioService();
                
                // 注意：窗口显示由App.xaml.cs处理，这里不需要调用ShowWindow()
                // ShowWindow()方法用于热键切换显示/隐藏，不用于初始显示
                
                // 添加调试输出
                System.Diagnostics.Debug.WriteLine("MainWindow initialized and shown");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"MainWindow构造函数异常: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                MessageBox.Show($"窗口初始化失败: {ex.Message}\n\n详细信息: {ex.StackTrace}", "初始化错误", MessageBoxButton.OK, MessageBoxImage.Error);
                throw; // 重新抛出异常，让App.xaml.cs处理
            }
        }

        private async void LoadMapPasswordsAsync()
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("开始加载地图密码...");
                var mapPasswordService = MapPasswordService.Instance;
                var data = await mapPasswordService.GetMapPasswordsAsync();
                
                await Dispatcher.InvokeAsync(() =>
                {
                    if (data != null && data.Maps != null && data.Maps.Count > 0)
                    {
                        MapPasswordList.ItemsSource = data.Maps;
                        System.Diagnostics.Debug.WriteLine($"成功加载了 {data.Maps.Count} 个地图密码");
                    }
                    else
                    {
                        MapPasswordList.ItemsSource = null;
                        System.Diagnostics.Debug.WriteLine("未获取到地图密码数据 - data为null或Maps为空");
                    }
                });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载地图密码失败: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"错误类型: {ex.GetType().Name}");
                System.Diagnostics.Debug.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                await Dispatcher.InvokeAsync(() =>
                {
                    // 加载失败时不显示任何内容
                });
            }
        }
        
        private void InitializePriceFilter()
        {
            var priceRanges = new List<string> { "全部", "0-15万", "16-30万", "31-60万", "60万以上" };
            PriceFilter.ItemsSource = priceRanges;
        }
        
        private void InitializeWeaponFilter()
        {
            // 确保具体武器筛选器初始状态为禁用
            WeaponFilter.IsEnabled = false;
            WeaponFilter.ItemsSource = null;
            WeaponFilter.SelectedItem = null;
            // 设置提示文字在XAML中已设置，但这里再次确保
            MaterialDesignThemes.Wpf.HintAssist.SetHint(WeaponFilter, "先选择武器类型");
        }
        
        private async Task LoadCategoriesAsync()
        {
            try
            {
                List<string> categories;
                if (_isAobMode)
                {
                    categories = await dbManager.GetCategoriesAobAsync();
                }
                else
                {
                    categories = await dbManager.GetCategoriesAsync();
                }
                
                await Dispatcher.InvokeAsync(() =>
                {
                    // 在列表前添加"全部"选项
                    var allCategories = new List<string> { "全部" };
                    allCategories.AddRange(categories);
                    CategoryFilter.ItemsSource = allCategories;
                    System.Diagnostics.Debug.WriteLine($"加载了 {categories.Count} 个武器分类 (模式: {(_isAobMode ? "全面战场" : "烽火地带")})");
                });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载分类数据失败: {ex.Message}");
            }
        }
        
        private async Task LoadWeaponsAsync(string? category = null)
        {
            try
            {
                List<string> weapons;
                if (_isAobMode)
                {
                    weapons = await dbManager.GetWeaponsAobAsync(category);
                }
                else
                {
                    weapons = await dbManager.GetWeaponsAsync(category);
                }
                
                await Dispatcher.InvokeAsync(() =>
                {
                    // 在列表前添加"全部"选项
                    var allWeapons = new List<string> { "全部" };
                    allWeapons.AddRange(weapons);
                    WeaponFilter.ItemsSource = allWeapons;
                    WeaponFilter.IsEnabled = true; // 启用具体武器筛选器
                    WeaponFilter.SelectedItem = null; // 清除选择
                    System.Diagnostics.Debug.WriteLine($"加载了 {weapons.Count} 个武器 (分类: {category ?? "全部"}, 模式: {(_isAobMode ? "全面战场" : "烽火地带")})");
                });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载武器数据失败: {ex.Message}");
            }
        }
        
        private async Task LoadSchemesAsync(string? category = null, string? weaponName = null, string? priceRange = null, string? searchText = null, string? sortBy = null, bool append = false)
        {
            // 取消之前的加载操作
            _loadCancellationToken?.Cancel();
            _loadCancellationToken = new System.Threading.CancellationTokenSource();
            var cancellationToken = _loadCancellationToken.Token;
            
            // 如果不是追加模式，重置分页
            if (!append)
            {
                _currentPage = 1;
                _hasMoreData = true;
                _allItems.Clear();
            }
            
            // 防止重复加载
            if (_isLoading)
            {
                System.Diagnostics.Debug.WriteLine("⚠ 正在加载中，已取消上次请求");
            }
            
            _isLoading = true;
            _loadTimer.Restart();
            
            try
            {
                if (category == "全部") category = null;
                if (weaponName == "全部") weaponName = null;
                if (priceRange == "全部") priceRange = null;
                if (string.IsNullOrWhiteSpace(searchText)) searchText = null;
                if (_isAobMode) priceRange = null;
                if (sortBy == null) sortBy = _currentSortBy;
                
                System.Diagnostics.Debug.WriteLine($"📄 开始加载方案数据... (第{_currentPage}页, 每页{PAGE_SIZE}个, 模式: {(_isAobMode ? "全面战场" : "烽火地带")}, 分类: {category ?? "全部"}, 武器: {weaponName ?? "全部"}, 价格: {priceRange ?? "全部"}, 搜索: {searchText ?? "无"}, 排序: {sortBy ?? "默认"})");
                
                // 检查是否已取消
                if (cancellationToken.IsCancellationRequested)
                {
                    System.Diagnostics.Debug.WriteLine("⚠ 加载已取消");
                    return;
                }
                
                List<Scheme> schemesData;
                if (_isAobMode)
                {
                    schemesData = await dbManager.GetSchemesAobAsync(category, weaponName, searchText, sortBy);
                }
                else
                {
                    schemesData = await dbManager.GetSchemesAsync(category, weaponName, priceRange, searchText, sortBy);
                }
                
                // 再次检查是否已取消
                if (cancellationToken.IsCancellationRequested)
                {
                    System.Diagnostics.Debug.WriteLine("⚠ 加载已取消");
                    return;
                }
                
                System.Diagnostics.Debug.WriteLine($"✓ 从数据库获取到 {schemesData.Count} 条方案数据");
                
                // 获取广告数据
                List<Advert> advertsData = new List<Advert>();
                try
                {
                    var advertService = AdvertService.Instance;
                    advertsData = await advertService.GetAdvertsAsync();
                    System.Diagnostics.Debug.WriteLine($"获取到 {advertsData.Count} 个广告");
                }
                catch (Exception adEx)
                {
                    System.Diagnostics.Debug.WriteLine($"获取广告数据失败: {adEx.Message}");
                    // 广告加载失败不影响主要功能
                }
                
                // 实现分页：只取当前页的数据
                int skip = (_currentPage - 1) * PAGE_SIZE;
                var pagedSchemes = schemesData.Skip(skip).Take(PAGE_SIZE).ToList();
                
                // 检查是否还有更多数据
                _hasMoreData = schemesData.Count > (_currentPage * PAGE_SIZE);
                
                System.Diagnostics.Debug.WriteLine($"📄 当前页数据: {pagedSchemes.Count}个, 总数据: {schemesData.Count}个, 还有更多: {_hasMoreData}");
                
                // 判断是否有筛选条件，如果有则不显示广告
                bool hasFilter = HasActiveFilters(category, weaponName, priceRange, searchText, sortBy);
                System.Diagnostics.Debug.WriteLine($"📊 筛选状态: {(hasFilter ? "有筛选条件，不显示广告" : "无筛选条件，显示广告")}");
                
                // 使用插入算法整合广告和方案（只对当前页）
                var insertionAlgorithm = new AdvertInsertionAlgorithm();
                var finalList = insertionAlgorithm.InsertAdverts(pagedSchemes, (append || hasFilter) ? new List<Advert>() : advertsData);
                
                // 检查是否已取消
                if (cancellationToken.IsCancellationRequested)
                {
                    System.Diagnostics.Debug.WriteLine("⚠ 加载已取消");
                    return;
                }
                
                // 使用ListBox的ItemsSource并添加企业级动画效果
                await Dispatcher.InvokeAsync(async () =>
                {
                    if (append)
                    {
                        // 追加模式：添加到现有列表
                        foreach (var item in finalList)
                        {
                            _allItems.Add(item);
                        }
                        SchemesList.ItemsSource = null;
                        SchemesList.ItemsSource = _allItems;
                        System.Diagnostics.Debug.WriteLine($"✓ 追加 {finalList.Count} 个项目，总计 {_allItems.Count} 个");
                        
                        // 为新加载的卡片添加交错动画（只对新增项）
                        await Task.Delay(50); // 等待渲染完成
                        await UIInteractionService.Instance.AnimateCardLoadingAsync(SchemesList, useStagger: true);
                    }
                    else
                    {
                        // 新加载模式：替换列表
                        _allItems = new List<object>(finalList);
                        SchemesList.ItemsSource = _allItems;
                        System.Diagnostics.Debug.WriteLine($"✓ 加载 {_allItems.Count} 个项目");
                        
                        // 为所有卡片添加企业级交错加载动画
                        await Task.Delay(100); // 等待渲染完成
                        await UIInteractionService.Instance.AnimateCardLoadingAsync(SchemesList, useStagger: true);
                        
                        // 为所有卡片添加企业级悬停效果
                        InitializeCardInteractions();
                    }
                    
                    // 更新价格字段的可见性
                    UpdatePriceVisibility();
                    
                    // 更新"加载更多"按钮可见性
                    LoadMoreButton.Visibility = _hasMoreData ? Visibility.Visible : Visibility.Collapsed;
                }, System.Windows.Threading.DispatcherPriority.Background);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载方案数据失败: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"错误堆栈: {ex.StackTrace}");
                MessageBox.Show($"加载方案数据失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                _isLoading = false;
                _loadTimer.Stop();
                System.Diagnostics.Debug.WriteLine($"⏱ 数据加载耗时: {_loadTimer.ElapsedMilliseconds}ms");
            }
        }
        
        private void UpdatePriceVisibility()
        {
            // 在全面战场模式下隐藏价格筛选器和价格显示
            var visibility = _isAobMode ? Visibility.Collapsed : Visibility.Visible;
            PriceLabel.Visibility = visibility;
            PriceFilter.Visibility = visibility;
        }
        
        private async void ModeTabControl_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            var oldIndex = _isAobMode ? 1 : 0;
            var newIndex = ModeTabControl.SelectedIndex;
            
            // 企业级模式切换动画
            await UIInteractionService.Instance.AnimateModeSwitchAsync(ModeTabControl, oldIndex, newIndex);
            
            if (ModeTabControl.SelectedIndex == 0)
            {
                // 烽火地带模式
                _isAobMode = false;
            }
            else
            {
                // 全面战场模式
                _isAobMode = true;
            }
            
            // 清除所有筛选条件
            CategoryFilter.SelectedItem = null;
            WeaponFilter.SelectedItem = null;
            WeaponFilter.ItemsSource = null;
            WeaponFilter.IsEnabled = false; // 禁用具体武器筛选器
            PriceFilter.SelectedItem = null;
            SearchBox.Text = string.Empty;
            
            // 重置排序为默认（热门方案）
            _currentSortBy = "hot";
            UpdateSortButtonStates();
            
            // 重新加载分类列表
            await LoadCategoriesAsync();
            // 不加载武器列表，因为没有选择武器类型
            
            // 更新价格筛选器可见性
            UpdatePriceVisibility();
            
            // 重新加载方案
            await RefreshSchemesList();
        }
        
        private async void CategoryFilter_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            // 企业级筛选器弹出动画
            await UIInteractionService.Instance.AnimateFilterPopupAsync(CategoryFilter);
            
            var selectedCategory = CategoryFilter.SelectedItem as string;
            
            // 清除武器选择
            WeaponFilter.SelectedItem = null;
            
            if (string.IsNullOrEmpty(selectedCategory) || selectedCategory == "全部")
            {
                // 未选择具体武器类型时，禁用具体武器筛选器
                WeaponFilter.ItemsSource = null;
                WeaponFilter.IsEnabled = false;
                MaterialDesignThemes.Wpf.HintAssist.SetHint(WeaponFilter, "先选择武器类型");
                System.Diagnostics.Debug.WriteLine("武器类型未选择，禁用具体武器筛选器");
            }
            else
            {
                // 选择了具体武器类型，加载该分类下的武器列表
                await LoadWeaponsAsync(selectedCategory);
                // 更新提示文字
                await Dispatcher.InvokeAsync(() =>
                {
                    // 使用反射或直接设置Hint，这里我们通过重新设置来更新
                    MaterialDesignThemes.Wpf.HintAssist.SetHint(WeaponFilter, "选择具体武器");
                });
            }
            
            await RefreshSchemesList();
        }
        
        private async void WeaponFilter_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            // 企业级筛选器弹出动画
            await UIInteractionService.Instance.AnimateFilterPopupAsync(WeaponFilter);
            await RefreshSchemesList();
        }
        
        private async void PriceFilter_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            // 企业级筛选器弹出动画
            await UIInteractionService.Instance.AnimateFilterPopupAsync(PriceFilter);
            await RefreshSchemesList();
        }
        
        private async Task RefreshSchemesList()
        {
            var selectedCategory = CategoryFilter.SelectedItem as string;
            var selectedWeapon = WeaponFilter.SelectedItem as string;
            var selectedPrice = PriceFilter.SelectedItem as string;
            var searchText = SearchBox.Text;
            
            await LoadSchemesAsync(selectedCategory, selectedWeapon, selectedPrice, searchText, _currentSortBy);
        }
        
        /// <summary>
        /// 判断是否有活动的筛选条件
        /// </summary>
        private bool HasActiveFilters(string? category, string? weaponName, string? priceRange, string? searchText, string? sortBy)
        {
            // 检查武器类型筛选（除了"全部"和空值）
            bool hasCategoryFilter = !string.IsNullOrEmpty(category) && category != "全部";
            
            // 检查具体武器筛选（除了"全部"和空值）
            bool hasWeaponFilter = !string.IsNullOrEmpty(weaponName) && weaponName != "全部";
            
            // 检查价格范围筛选（除了"全部"和空值，且非AOB模式）
            bool hasPriceFilter = !_isAobMode && !string.IsNullOrEmpty(priceRange) && priceRange != "全部";
            
            // 检查搜索文本
            bool hasSearchFilter = !string.IsNullOrWhiteSpace(searchText);
            
            // 检查排序方式（除了默认的"hot"）
            bool hasSortFilter = !string.IsNullOrEmpty(sortBy) && sortBy != "hot";
            
            return hasCategoryFilter || hasWeaponFilter || hasPriceFilter || hasSearchFilter || hasSortFilter;
        }
        
        private async void HotSchemeBtn_Click(object sender, RoutedEventArgs e)
        {
            _currentSortBy = "hot";
            UpdateSortButtonStates();
            await RefreshSchemesList();
        }
        
        private async void LatestSchemeBtn_Click(object sender, RoutedEventArgs e)
        {
            _currentSortBy = "latest";
            UpdateSortButtonStates();
            await RefreshSchemesList();
        }
        
        private void ShareSchemeBtn_Click(object sender, RoutedEventArgs e)
        {
            // 暂停主窗口的置顶定时器，避免抢焦点
            bool timerWasRunning = false;
            if (_topmostTimer != null && _topmostTimer.IsEnabled)
            {
                _topmostTimer.Stop();
                timerWasRunning = true;
            }
            
            try
            {
                var publishWindow = new PublishSchemeWindow(_isAobMode)
                {
                    Owner = this
                };
                publishWindow.ShowDialog();
                
                // 如果发布成功，刷新方案列表
                if (publishWindow.DialogResult == true)
                {
                    _ = RefreshSchemesList();
                }
            }
            finally
            {
                // 恢复主窗口的置顶定时器
                if (timerWasRunning && _topmostTimer != null)
                {
                    _topmostTimer.Start();
                }
            }
        }
        
        private void UpdateSortButtonStates()
        {
            // 更新按钮样式，显示选中状态
            if (_currentSortBy == "hot")
            {
                HotSchemeBtn.Background = System.Windows.Media.Brushes.Orange;
                LatestSchemeBtn.Background = System.Windows.Media.Brushes.Transparent;
            }
            else if (_currentSortBy == "latest")
            {
                HotSchemeBtn.Background = System.Windows.Media.Brushes.Transparent;
                LatestSchemeBtn.Background = System.Windows.Media.Brushes.Orange;
            }
            else
            {
                HotSchemeBtn.Background = System.Windows.Media.Brushes.Transparent;
                LatestSchemeBtn.Background = System.Windows.Media.Brushes.Transparent;
            }
        }
        
        private System.Windows.Threading.DispatcherTimer? _searchTimer;
        
        private async void LoadMoreButton_Click(object sender, RoutedEventArgs e)
        {
            if (!_hasMoreData || _isLoading)
            {
                return;
            }
            
            _currentPage++;
            
            var selectedCategory = CategoryFilter.SelectedItem as string;
            var selectedWeapon = WeaponFilter.SelectedItem as string;
            var selectedPrice = PriceFilter.SelectedItem as string;
            var searchText = SearchBox.Text;
            
            // 追加模式加载
            await LoadSchemesAsync(selectedCategory, selectedWeapon, selectedPrice, searchText, _currentSortBy, append: true);
        }
        
        private void SearchBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            // 使用防抖机制，延迟300ms后执行搜索（已优化，配合缓存更快响应）
            if (_searchTimer == null)
            {
                // 只创建一次定时器
                _searchTimer = new System.Windows.Threading.DispatcherTimer
                {
                    Interval = TimeSpan.FromMilliseconds(300)
                };
                _searchTimer.Tick += SearchTimer_Tick;
            }
            else
            {
                // 重用现有定时器，重置计时
                _searchTimer.Stop();
            }
            
            _searchTimer.Start();
        }
        
        private async void SearchTimer_Tick(object? sender, EventArgs e)
        {
            _searchTimer?.Stop();
            await RefreshSchemesList();
        }
        
        private async void SearchBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
            {
                // 如果按Enter键，立即搜索
                if (_searchTimer != null)
                {
                    _searchTimer.Stop();
                }
                await RefreshSchemesList();
            }
        }
        
        private void MinimizeBtn_Click(object sender, RoutedEventArgs e)
        {
            // 使用动画隐藏而不是直接最小化，避免鼠标卡顿
            HideWindowWithAnimation();
        }
        
        private void SettingsBtn_Click(object sender, RoutedEventArgs e)
        {
            // 暂停主窗口的置顶定时器，避免抢焦点
            bool timerWasRunning = false;
            if (_topmostTimer != null && _topmostTimer.IsEnabled)
            {
                _topmostTimer.Stop();
                timerWasRunning = true;
            }
            
            try
            {
                var settingsWindow = new SettingsWindow
                {
                    Owner = this
                };
                settingsWindow.ShowDialog();
            }
            finally
            {
                // 恢复主窗口的置顶定时器
                if (timerWasRunning && _topmostTimer != null)
                {
                    _topmostTimer.Start();
                }
            }
        }
        
        private void CloseBtn_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
        
        private void LogoutBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 确认退出登录
                var result = MessageBox.Show("确定要退出登录吗？", "退出登录", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {
                    // 注销登录
                    AuthService.Logout();
                    
                    // 隐藏主窗口
                    this.Hide();
                    
                    // 通过App显示登录窗口
                    if (Application.Current is App app)
                    {
                        app.ShowLoginWindow();
                    }
                    else
                    {
                        // 如果无法获取App实例，直接显示登录窗口
                        var loginWindow = new LoginWindow();
                        var loginResult = loginWindow.ShowDialog();
                        
                        if (loginResult == true && loginWindow.IsLoggedIn)
                        {
                            // 重新登录成功，重新加载用户信息并显示主窗口
                            LoadUserInfo();
                            this.Show();
                            this.Activate();
                            this.Focus();
                        }
                        else
                        {
                            // 取消登录或登录失败，关闭应用程序
                            Application.Current.Shutdown();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"退出登录时发生错误: {ex.Message}");
                MessageBox.Show($"退出登录时发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                
                // 即使出错也要尝试清理登录状态
                try
                {
                    AuthService.Logout();
                }
                catch { }
            }
        }
        
        public void LoadUserInfo()
        {
            try
            {
                var user = AuthService.GetCurrentUser();
                var isLoggedIn = AuthService.IsLoggedIn();
                
                if (isLoggedIn && user != null)
                {
                    // 显示用户信息
                    UsernameText.Text = user.Username ?? "未知用户";
                    LoginStatusText.Text = "已登录";
                    System.Diagnostics.Debug.WriteLine($"用户信息已加载: {user.Username}");
                }
                else
                {
                    // 未登录状态
                    UsernameText.Text = "未登录";
                    LoginStatusText.Text = "未登录";
                    System.Diagnostics.Debug.WriteLine("用户未登录");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载用户信息失败: {ex.Message}");
                UsernameText.Text = "加载失败";
                LoginStatusText.Text = "未知";
            }
        }
        
        private async void CopyScheme_Click(object sender, RoutedEventArgs e)
        {
            Button? button = null;
            object? originalContent = null;
            int schemeId = -1;
            
            try
            {
                if (sender is Button btn && btn.Tag is Scheme scheme)
                {
                    button = btn;
                    schemeId = scheme.Id;
                    
                    // 防止重复点击同一方案
                    lock (_copyingSchemeIds)
                    {
                        if (_copyingSchemeIds.Contains(schemeId))
                        {
                            System.Diagnostics.Debug.WriteLine($"方案 {schemeId} 正在处理中，忽略重复点击");
                            return;
                        }
                        _copyingSchemeIds.Add(schemeId);
                    }
                    
                    System.Diagnostics.Debug.WriteLine($"复制方案: ID={scheme.Id}, 武器={scheme.WeaponName}");
                    
                    // 企业级按钮点击动画反馈
                    await button.AnimateCardClickAsync();
                    
                    // 禁用按钮防止重复点击
                    button.IsEnabled = false;
                    originalContent = button.Content;
                    button.Content = "处理中...";
                    
                    try
                    {
                        // 先调用API增加使用次数
                        var usageService = SchemeUsageService.Instance;
                        var result = await usageService.IncreaseUsageAsync(scheme.Id, _isAobMode);
                        
                        if (result.Success)
                        {
                            // 更新本地使用次数
                            scheme.Uses = result.SchemeUses;
                            System.Diagnostics.Debug.WriteLine($"✓ 使用次数增加成功: 方案={result.SchemeUses}, 全局={result.GlobalTotalUses}");
                        }
                        else
                        {
                            // API调用失败时只记录日志，不影响复制功能
                            System.Diagnostics.Debug.WriteLine($"✗ 使用次数增加失败: {result.Message}");
                            
                            // 只显示超时错误提示，冷却期错误不显示提示（用户可以正常使用）
                            if (result.ErrorType == "timeout")
                            {
                                ShowUsageNotification($"⚠️ {result.Message}", false);
                            }
                            // 注释掉冷却期提示，让用户可以无感地重复使用方案
                            // else if (result.ErrorType == "cooldown")
                            // {
                            //     ShowUsageNotification($"⏰ {result.Message}", false);
                            // }
                        }
                        
                        // 无论API是否成功，都复制方案内容
                        if (!string.IsNullOrEmpty(scheme.SchemeContent))
                        {
                            // 使用安全的剪贴板操作（带重试机制）
                            bool success = ClipboardHelper.SetText(scheme.SchemeContent);
                            
                            if (success)
                            {
                                ShowCopyNotification();
                                System.Diagnostics.Debug.WriteLine($"✓ 方案内容已复制到剪贴板: {scheme.WeaponName}");
                            }
                            else
                            {
                                // 剪贴板操作失败，显示友好提示
                                ShowUsageNotification("⚠️ 复制失败，剪贴板被占用，请稍后重试", false);
                                System.Diagnostics.Debug.WriteLine($"✗ 剪贴板操作失败: {scheme.WeaponName}");
                            }
                        }
                    }
                    catch (Exception innerEx)
                    {
                        System.Diagnostics.Debug.WriteLine($"复制过程异常: {innerEx.Message}");
                        ShowUsageNotification($"⚠️ 复制异常: {innerEx.Message}", false);
                    }
                    finally
                    {
                        // 确保按钮状态总是能恢复
                        if (button != null)
                        {
                            button.IsEnabled = true;
                            if (originalContent != null)
                            {
                                button.Content = originalContent;
                            }
                        }
                        
                        // 从正在处理的集合中移除
                        lock (_copyingSchemeIds)
                        {
                            _copyingSchemeIds.Remove(schemeId);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"复制方案失败: {ex.Message}");
                MessageBox.Show($"复制失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                
                // 确保在异常情况下也能恢复按钮状态
                if (button != null)
                {
                    button.IsEnabled = true;
                    if (originalContent != null)
                    {
                        button.Content = originalContent;
                    }
                }
                
                // 确保从正在处理的集合中移除
                if (schemeId != -1)
                {
                    lock (_copyingSchemeIds)
                    {
                        _copyingSchemeIds.Remove(schemeId);
                    }
                }
            }
        }
        
        /// <summary>
        /// 认证徽标点击事件 - 打开社交链接
        /// </summary>
        private void PartnerBadge_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (sender is Button button && button.Tag is Scheme scheme)
                {
                    // 检查是否有社交链接
                    if (!string.IsNullOrEmpty(scheme.SocialLink))
                    {
                        // 处理链接格式，确保有协议前缀
                        string url = scheme.SocialLink;
                        if (!url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && 
                            !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
                        {
                            url = "https://" + url;
                            System.Diagnostics.Debug.WriteLine($"[认证徽标] 自动添加https://前缀: {url}");
                        }
                        
                        System.Diagnostics.Debug.WriteLine($"[认证徽标] 打开社交链接: {url}");
                        
                        // 使用默认浏览器打开链接
                        try
                        {
                            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                            {
                                FileName = url,
                                UseShellExecute = true
                            });
                            
                            System.Diagnostics.Debug.WriteLine($"✓ 社交链接已打开: {url}");
                        }
                        catch (Exception openEx)
                        {
                            System.Diagnostics.Debug.WriteLine($"✗ 打开链接失败: {openEx.Message}");
                            MessageBox.Show($"无法打开链接: {openEx.Message}", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                        }
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine($"[认证徽标] 该用户未设置社交链接: {scheme.UserName}");
                        MessageBox.Show($"{scheme.UserName} 暂未设置社交链接", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"[认证徽标] 点击处理失败: {ex.Message}");
                MessageBox.Show($"操作失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        
        // 注意：OnImageLoaded方法已删除，图片通过数据绑定自动更新
        
        private async void AdvertCard_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (sender is Button button && button.Tag is Advert advert)
                {
                    // 记录广告点击统计
                    _ = Task.Run(async () =>
                    {
                        try
                        {
                            var advertService = AdvertService.Instance;
                            await advertService.RecordAdvertClickAsync(advert.Id);
                            System.Diagnostics.Debug.WriteLine($"广告点击统计已记录: {advert.Id}");
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine($"记录广告点击失败: {ex.Message}");
                        }
                    });
                    
                    // 打开广告链接
                    if (!string.IsNullOrEmpty(advert.LinkUrl))
                    {
                        System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                        {
                            FileName = advert.LinkUrl,
                            UseShellExecute = true
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"打开广告链接失败: {ex.Message}");
                MessageBox.Show($"打开链接失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        
        private static DateTime _lastCopyNotificationTime = DateTime.MinValue;
        
        private void ShowCopyNotification()
        {
            // 防止短时间内多次显示复制提示（2秒内只显示一次）
            var now = DateTime.Now;
            if ((now - _lastCopyNotificationTime).TotalSeconds < 2)
            {
                return;
            }
            _lastCopyNotificationTime = now;
            
            // 创建一个简单的通知
            var notification = new TextBlock
            {
                Text = "方案已复制到剪贴板",
                Style = (Style)FindResource("ContentTextStyle"),
                Background = new SolidColorBrush(Color.FromRgb(255, 107, 107)), // 红色背景
                Foreground = System.Windows.Media.Brushes.White,
                Padding = new Thickness(10),
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Bottom
            };
            
            // 将通知添加到ListBox上方
            var mainGrid = (Grid)Content;
            var contentGrid = (Grid)mainGrid.Children[1]; // 获取内容区域的Grid
            // Grid现在有5行：标题0，今日密码1，Tab2，筛选器3，列表4
            var listBox = (System.Windows.Controls.ListBox)contentGrid.Children[4]; // 获取ListBox (现在是Row 4)
            
            // 创建一个覆盖层来显示通知
            var overlay = new Grid
            {
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Bottom,
                Margin = new Thickness(0, 0, 0, 10),
                IsHitTestVisible = false // 允许点击穿透
            };
            overlay.Children.Add(notification);
            
            contentGrid.Children.Add(overlay);
            Grid.SetRow(overlay, 4);
            
            // 3秒后移除通知
            var timer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(3)
            };
            timer.Tick += (s, e) =>
            {
                contentGrid.Children.Remove(overlay);
                timer.Stop();
            };
            timer.Start();
        }
        
        private void ShowUsageNotification(string message, bool isSuccess = true)
        {
            // 创建通知
            var notification = new TextBlock
            {
                Text = message,
                Style = (Style)FindResource("ContentTextStyle"),
                Background = isSuccess ? System.Windows.Media.Brushes.Green : System.Windows.Media.Brushes.OrangeRed,
                Foreground = System.Windows.Media.Brushes.White,
                Padding = new Thickness(10),
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Bottom,
                TextWrapping = TextWrapping.Wrap
            };
            
            // 将通知添加到ListBox上方
            var mainGrid = (Grid)Content;
            var contentGrid = (Grid)mainGrid.Children[1];
            
            // 创建覆盖层
            var overlay = new Grid
            {
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Bottom,
                Margin = new Thickness(0, 0, 0, 10),
                IsHitTestVisible = false
            };
            overlay.Children.Add(notification);
            
            contentGrid.Children.Add(overlay);
            Grid.SetRow(overlay, 4);
            
            // 3秒后移除通知
            var timer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(3)
            };
            timer.Tick += (s, e) =>
            {
                contentGrid.Children.Remove(overlay);
                timer.Stop();
            };
            timer.Start();
        }
        
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            // 窗口加载完成后注册热键
            RegisterHotKey();
            // 注册后再次更新标题（以确保提示一致）
            UpdateWindowTitleWithHotkey();
            
            // 确保具体武器筛选器的初始状态正确
            WeaponFilter.IsEnabled = false;
            WeaponFilter.ItemsSource = null;
            MaterialDesignThemes.Wpf.HintAssist.SetHint(WeaponFilter, "先选择武器类型");
            
            // 确保窗口在顶层
            this.Topmost = true;
            ForceWindowToTop();
            
            // 启动定时器，定期检查窗口置顶状态（每1秒检查一次，不抢夺焦点）
            _topmostTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMilliseconds(1000)
            };
            _topmostTimer.Tick += (s, args) =>
            {
                // 只在窗口可见时确保置顶属性，但不强制抢夺焦点
                if (this.Visibility == Visibility.Visible && !this.Topmost)
                {
                    this.Topmost = true;
                    System.Diagnostics.Debug.WriteLine("窗口置顶状态已恢复（不抢夺焦点）");
                }
            };
            _topmostTimer.Start();
        }
        
        private void MainWindow_Activated(object sender, EventArgs e)
        {
            // 窗口激活时确保在顶层，但不再次抢夺焦点
            if (!this.Topmost)
            {
                this.Topmost = true;
                System.Diagnostics.Debug.WriteLine("窗口激活时恢复置顶状态");
            }
        }
        
        private void MainWindow_Deactivated(object sender, EventArgs e)
        {
            // 窗口失去焦点时保持置顶显示，但不抢夺焦点（允许用户点击游戏）
            // 只设置Topmost属性，让窗口保持在其他窗口上层但不抢夺焦点
            this.Topmost = true;
            System.Diagnostics.Debug.WriteLine("窗口失活，保持置顶但不抢夺焦点");
        }
        
        private void MainWindow_Closed(object sender, EventArgs e)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("MainWindow正在关闭，清理资源...");
                
                // 取消所有正在进行的加载操作
                _loadCancellationToken?.Cancel();
                _loadCancellationToken?.Dispose();
                
                // 停止并清理定时器
                if (_topmostTimer != null)
                {
                    _topmostTimer.Stop();
                    _topmostTimer = null;
                }
                
                if (_searchTimer != null)
                {
                    _searchTimer.Stop();
                    _searchTimer.Tick -= SearchTimer_Tick;
                    _searchTimer = null;
                }
                
                // 注销热键
                UnregisterHotKey();
                
                // 取消订阅事件，防止内存泄漏
                this.Loaded -= MainWindow_Loaded;
                this.Activated -= MainWindow_Activated;
                this.Deactivated -= MainWindow_Deactivated;
                this.Closed -= MainWindow_Closed;
                
                // 清理列表数据，释放内存
                _allItems.Clear();
                SchemesList.ItemsSource = null;
                schemes?.Clear();
                
                // 清理音频服务资源
                try
                {
                    AudioService.Instance.Dispose();
                    System.Diagnostics.Debug.WriteLine("✓ 音频服务资源已清理");
                }
                catch (Exception audioEx)
                {
                    System.Diagnostics.Debug.WriteLine($"清理音频服务资源失败: {audioEx.Message}");
                }
                
                System.Diagnostics.Debug.WriteLine("✓ 资源清理完成");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"清理资源时出错: {ex.Message}");
            }
        }

        private void RegisterHotKey()
        {
            try
            {
                // 使用系统级热键注册（RegisterHotKey），这是真正的系统级别，像Alt+F4一样
                // 获取窗口句柄，如果还没有创建则确保创建
                var helper = new WindowInteropHelper(this);
                var hwnd = helper.EnsureHandle();
                
                // 检查句柄是否有效
                if (hwnd == IntPtr.Zero)
                {
                    System.Diagnostics.Debug.WriteLine("窗口句柄无效，延迟注册热键");
                    // 使用DispatcherTimer延迟重试，不阻塞UI线程
                    var timer = new DispatcherTimer
                    {
                        Interval = TimeSpan.FromMilliseconds(100)
                    };
                    timer.Tick += (s, e) =>
                    {
                        timer.Stop();
                        RegisterHotKey();
                    };
                    timer.Start();
                    return;
                }
                
                // 先尝试注销可能存在的旧热键
                try
                {
                    HotkeyManager.UnregisterHotKey(hwnd, HOTKEY_ID);
                    HotkeyManager.UnregisterHotKey(hwnd, AUDIO_HOTKEY_ID);
                }
                catch { }
                
                // 先添加窗口消息钩子（必须在注册热键之前）
                try
                {
                    var source = HwndSource.FromHwnd(hwnd);
                    if (source == null)
                    {
                        // 如果获取不到HwndSource，延迟重试
                        System.Diagnostics.Debug.WriteLine("Failed to get HwndSource, will retry...");
                        var timer = new DispatcherTimer
                        {
                            Interval = TimeSpan.FromMilliseconds(500)
                        };
                        timer.Tick += (s, e) =>
                        {
                            timer.Stop();
                            RegisterHotKey();
                        };
                        timer.Start();
                        return;
                    }
                    
                    // 确保钩子已添加
                    source.RemoveHook(WndProc); // 先移除，避免重复添加
                    source.AddHook(WndProc);
                    System.Diagnostics.Debug.WriteLine("Window message hook added successfully");
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"添加窗口消息钩子失败: {ex.Message}");
                }
                
                // 注册系统级热键（RegisterHotKey是系统级别的，无论哪个程序在前台都能捕获）
                if (!HotkeyManager.RegisterHotKey(hwnd, HOTKEY_ID, _hotkeySettings.WinModifiers, _hotkeySettings.VirtualKeyCode))
                {
                    int errorCode = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                    System.Diagnostics.Debug.WriteLine($"Failed to register hotkey, error code: {errorCode}, will retry...");
                    
                    // 如果注册失败，可能是热键被占用，尝试使用低级钩子作为备用
                    if (LowLevelKeyboardHook.InstallHook(_hotkeySettings, () =>
                    {
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            ToggleWindowVisibility();
                        }), DispatcherPriority.Normal);
                    }))
                    {
                        System.Diagnostics.Debug.WriteLine($"Fallback: Low-level keyboard hook installed for {_hotkeySettings.HotkeyText}");
                    }
                    else
                    {
                        // 延迟重试注册热键
                        var timer = new DispatcherTimer
                        {
                            Interval = TimeSpan.FromMilliseconds(1000)
                        };
                        timer.Tick += (s, e) =>
                        {
                            timer.Stop();
                            RegisterHotKey();
                        };
                        timer.Start();
                    }
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"System-level hotkey {_hotkeySettings.HotkeyText} registered successfully (RegisterHotKey)");
                    
                    // 注册音频热键
                    if (!HotkeyManager.RegisterHotKey(hwnd, AUDIO_HOTKEY_ID, _hotkeySettings.AudioWinModifiers, _hotkeySettings.AudioVirtualKeyCode))
                    {
                        int errorCode = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                        System.Diagnostics.Debug.WriteLine($"Failed to register audio hotkey, error code: {errorCode}");
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine($"Audio hotkey {_hotkeySettings.AudioHotkeyText} registered successfully");
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"RegisterHotKey 发生异常: {ex.Message}");
                // 使用DispatcherTimer延迟重试，不阻塞UI线程
                var timer = new DispatcherTimer
                {
                    Interval = TimeSpan.FromMilliseconds(1000)
                };
                timer.Tick += (s, e) =>
                {
                    timer.Stop();
                    RegisterHotKey();
                };
                timer.Start();
            }
        }

        private void UnregisterHotKey()
        {
            try
            {
                // 卸载低级键盘钩子
                LowLevelKeyboardHook.UninstallHook();
                System.Diagnostics.Debug.WriteLine("Low-level keyboard hook uninstalled");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"卸载低级键盘钩子失败: {ex.Message}");
            }
            
            try
            {
                // 获取窗口句柄
                var helper = new WindowInteropHelper(this);
                var hwnd = helper.Handle;
                
                // 检查句柄是否有效
                if (hwnd == IntPtr.Zero)
                {
                    System.Diagnostics.Debug.WriteLine("窗口句柄无效，跳过热键注销");
                    return;
                }
                
                // 注销热键
                try
                {
                    HotkeyManager.UnregisterHotKey(hwnd, HOTKEY_ID);
                    HotkeyManager.UnregisterHotKey(hwnd, AUDIO_HOTKEY_ID);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"注销热键失败: {ex.Message}");
                }
                
                // 移除窗口消息钩子
                try
                {
                    var source = HwndSource.FromHwnd(hwnd);
                    if (source != null)
                    {
                        source.RemoveHook(WndProc);
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"移除窗口消息钩子失败: {ex.Message}");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"UnregisterHotKey 发生异常: {ex.Message}");
                // 忽略异常，避免影响窗口关闭
            }
        }

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            // 处理系统级热键消息（RegisterHotKey发送的消息）
            if (msg == HotkeyManager.WM_HOTKEY)
            {
                int id = wParam.ToInt32();
                if (id == HOTKEY_ID)
                {
                    // 系统级热键被按下，切换窗口显示/隐藏
                    System.Diagnostics.Debug.WriteLine($"{_hotkeySettings.HotkeyText} hotkey received via WM_HOTKEY message");
                    ToggleWindowVisibility();
                    handled = true;
                    return IntPtr.Zero;
                }
                else if (id == AUDIO_HOTKEY_ID)
                {
                    // 音频热键被按下，播放音频
                    System.Diagnostics.Debug.WriteLine($"{_hotkeySettings.AudioHotkeyText} audio hotkey received via WM_HOTKEY message");
                    PlayAudioAsync();
                    handled = true;
                    return IntPtr.Zero;
                }
            }
            return IntPtr.Zero;
        }

        private async void PlayAudioAsync()
        {
            try
            {
                string audioFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "11.mp3");
                System.Diagnostics.Debug.WriteLine($"=== 音频热键触发 ===");
                System.Diagnostics.Debug.WriteLine($"音频文件路径: {audioFilePath}");
                System.Diagnostics.Debug.WriteLine($"当前工作目录: {AppDomain.CurrentDomain.BaseDirectory}");
                System.Diagnostics.Debug.WriteLine($"文件是否存在: {File.Exists(audioFilePath)}");
                
                if (File.Exists(audioFilePath))
                {
                    var fileInfo = new FileInfo(audioFilePath);
                    System.Diagnostics.Debug.WriteLine($"文件大小: {fileInfo.Length} bytes");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("尝试查找其他位置的音频文件...");
                    // 尝试在几个可能的位置查找文件
                    string[] possiblePaths = {
                        Path.Combine(Directory.GetCurrentDirectory(), "11.mp3"),
                        Path.Combine(Environment.CurrentDirectory, "11.mp3"),
                        "11.mp3"
                    };
                    
                    foreach (string path in possiblePaths)
                    {
                        System.Diagnostics.Debug.WriteLine($"检查路径: {path}");
                        if (File.Exists(path))
                        {
                            audioFilePath = path;
                            System.Diagnostics.Debug.WriteLine($"找到音频文件: {audioFilePath}");
                            break;
                        }
                    }
                }
                
                var audioService = AudioService.Instance;
                // 使用游戏模式高优先级播放，确保在游戏中也能播放
                await audioService.PlayAudioInGameModeAsync(audioFilePath);
                System.Diagnostics.Debug.WriteLine($"=== 游戏模式高优先级音频播放请求已发送 ===");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"播放音频失败: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"异常详情: {ex}");
            }
        }

        private void ToggleWindowVisibility()
        {
            // 使用Dispatcher确保在UI线程执行
            Dispatcher.Invoke(() =>
            {
                if (this.Visibility == Visibility.Visible)
                {
                    HideWindowWithAnimation();
                }
                else
                {
                    ShowWindow();
                }
            });
        }

        private void ShowWindow()
        {
            ShowWindowWithAnimation();
        }

        /// <summary>
        /// 初始化动画配置 - 企业级优雅设置
        /// </summary>
        private void InitializeAnimationConfiguration()
        {
            // 根据系统性能和用户偏好配置动画效果
            var config = AnimationConfig.UltraElegant.Clone();
            
            // 根据窗口透明度调整动画配置
            if (_hotkeySettings.WindowOpacity < 0.9)
            {
                // 半透明窗口使用更快的动画
                config.ShowDuration = 200;
                config.HideDuration = 150;
                config.EnableShadow = false; // 半透明时禁用阴影避免视觉冲突
            }
            
            // 为按钮添加悬停效果
            AnimationService.Instance.SetConfiguration(config);
            
            // 为UI元素添加优雅的悬停效果
            this.Loaded += (s, e) =>
            {
                // 为所有按钮添加悬停缩放效果
                AddHoverEffectsToButtons();
            };
        }

        /// <summary>
        /// 为界面按钮添加悬停缩放效果
        /// </summary>
        private void AddHoverEffectsToButtons()
        {
            try
            {
                // 为主要控制按钮添加悬停效果
                if (MinimizeBtn != null)
                    AnimationService.Instance.AddHoverScaleEffect(MinimizeBtn, 1.1);
                    
                if (SettingsBtn != null)
                    AnimationService.Instance.AddHoverScaleEffect(SettingsBtn, 1.1);
                    
                if (CloseBtn != null)
                    AnimationService.Instance.AddHoverScaleEffect(CloseBtn, 1.1);

                // 为筛选按钮添加悬停效果（如果存在的话）
                try
                {
                    var filterBtn = this.FindName("FilterBtn") as FrameworkElement;
                    if (filterBtn != null)
                        AnimationService.Instance.AddHoverScaleEffect(filterBtn, 1.05);
                        
                    var sortBtn = this.FindName("SortBtn") as FrameworkElement;
                    if (sortBtn != null)
                        AnimationService.Instance.AddHoverScaleEffect(sortBtn, 1.05);
                        
                    var modeToggleBtn = this.FindName("ModeToggleBtn") as FrameworkElement;
                    if (modeToggleBtn != null)
                        AnimationService.Instance.AddHoverScaleEffect(modeToggleBtn, 1.05);
                }
                catch (Exception btnEx)
                {
                    System.Diagnostics.Debug.WriteLine($"添加筛选按钮效果时出错: {btnEx.Message}");
                }

                System.Diagnostics.Debug.WriteLine("按钮悬停效果已添加");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"添加按钮效果时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 初始化音频服务配置
        /// </summary>
        private void InitializeAudioService()
        {
            try
            {
                // 列出可用的音频设备（调试用）
                AudioService.Instance.ListAudioDevices();
                
                // 默认启用麦克风输出功能
                // 注意：需要安装虚拟音频线缆（如VB-Cable）才能使用此功能
                // 如果没有安装虚拟设备，音频将只输出到默认设备
                AudioService.Instance.EnableMicrophoneOutput(true);
                
                System.Diagnostics.Debug.WriteLine("=== 音频服务配置 ===");
                System.Diagnostics.Debug.WriteLine("麦克风输出模式：已启用");
                System.Diagnostics.Debug.WriteLine("提示：如果需要让语音聊天中的其他人听到音效，请安装VB-Audio Virtual Cable");
                System.Diagnostics.Debug.WriteLine("然后在语音软件中将麦克风设置为 'CABLE Output'");
                System.Diagnostics.Debug.WriteLine("====================");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"初始化音频服务失败: {ex.Message}");
                System.Diagnostics.Debug.WriteLine("将使用基础音频模式（不支持麦克风输出）");
            }
        }

        /// <summary>
        /// 初始化卡片交互效果 - 企业级悬停和点击反馈
        /// </summary>
        private void InitializeCardInteractions()
        {
            try
            {
                Dispatcher.BeginInvoke(() =>
                {
                    for (int i = 0; i < SchemesList.Items.Count; i++)
                    {
                        var container = SchemesList.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
                        if (container != null)
                        {
                            // 为每个卡片容器添加企业级悬停效果
                            container.AddEnterpriseHoverEffect(elevationEffect: true);
                            
                            // 查找卡片内的复制按钮并添加特殊效果
                            var copyButton = FindVisualChild<Button>(container);
                            if (copyButton != null)
                            {
                                copyButton.AddEnterpriseHoverEffect(elevationEffect: false);
                            }
                        }
                    }
                    System.Diagnostics.Debug.WriteLine("企业级卡片交互效果已初始化");
                }, DispatcherPriority.Background);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"初始化卡片交互效果时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// 查找可视化树中的子元素
        /// </summary>
        private T FindVisualChild<T>(DependencyObject parent) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                if (child is T found)
                    return found;

                var childOfChild = FindVisualChild<T>(child);
                if (childOfChild != null)
                    return childOfChild;
            }
            return null;
        }

        private void InitializeWindowBehavior()
        {
            // 暂时禁用窗口点击穿透，以便用户能看到窗口
            // WindowHelper.SetClickThrough(this, true);
            
            // 初始化窗口位置（屏幕中央，更容易看到）
            this.Left = (SystemParameters.WorkArea.Width - this.Width) / 2;
            this.Top = (SystemParameters.WorkArea.Height - this.Height) / 2;
        }

        private void SetupEventHandlers()
        {
            // 窗口鼠标事件
            this.MouseEnter += (s, e) =>
            {
                _isMouseOverWindow = true;
                if (_isAutoHideEnabled)
                {
                    ShowWindow();
                }
            };

            this.MouseLeave += (s, e) =>
            {
                _isMouseOverWindow = false;
                if (_isAutoHideEnabled)
                {
                    // 延迟隐藏，避免鼠标短暂离开时立即隐藏
                    var timer = new System.Windows.Threading.DispatcherTimer();
                    timer.Interval = TimeSpan.FromSeconds(1);
                    timer.Tick += (timerSender, timerArgs) =>
                    {
                        timer.Stop();
                        if (!_isMouseOverWindow)
                        {
                            HideWindowWithAnimation();
                        }
                    };
                    timer.Start();
                }
            };

            // 控制按钮事件
            // MinimizeBtn.Click 已在 XAML 中绑定到 MinimizeBtn_Click 方法
            // SettingsBtn.Click 已在 XAML 中绑定到 SettingsBtn_Click 方法
            CloseBtn.Click += (s, e) => CloseApplication();

            // 窗口默认置顶
            this.Topmost = true;

            // 窗口拖动支持
            this.MouseLeftButtonDown += (s, e) =>
            {
                if (e.ChangedButton == MouseButton.Left)
                {
                    this.DragMove();
                }
            };
        }

        private async void ShowWindowWithAnimation()
        {
            // 【焦点管理】保存当前前台窗口（游戏窗口），以便隐藏后返回焦点
            try
            {
                _previousForegroundWindow = NativeMethods.GetForegroundWindow();
                if (_previousForegroundWindow != IntPtr.Zero)
                {
                    System.Diagnostics.Debug.WriteLine($"[ShowWindow] 已保存前台窗口句柄: {_previousForegroundWindow}");
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"[ShowWindow] 保存前台窗口失败: {ex.Message}");
            }
            
            // 【鼠标控制】在全屏游戏中释放鼠标控制，确保用户可以操作界面
            try
            {
                MouseControlService.Instance.ReleaseMouse();
                System.Diagnostics.Debug.WriteLine("[ShowWindow] 鼠标控制已释放，用户可以操作界面");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"[ShowWindow] 释放鼠标控制失败: {ex.Message}");
            }
            
            // 预先重置缩放状态，防止任何残留的缩放值
            if (this.RenderTransform is ScaleTransform preScale)
            {
                preScale.ScaleX = 1.0;
                preScale.ScaleY = 1.0;
            }
            
            // 使用企业级动画服务 - 创建丝滑的显示效果
            // 使用优化的配置：只使用透明度渐变，移除缩放效果
            var config = AnimationConfig.Subtle.Clone();
            config.ScaleFrom = 1.0;  // 移除缩放效果，保持原始大小
            config.ScaleTo = 1.0;    // 移除缩放效果，保持原始大小
            config.OpacityFrom = 0.0;
            config.OpacityTo = 1.0;
            config.ShowDuration = 280;
            config.EnableShadow = false;  // 保持轻量
            
            await AnimationService.Instance.ShowWindowWithScaleAsync(this, () =>
            {
                // 动画完成后确保窗口置顶和正确缩放
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    // 确保最终状态正确
                    if (this.RenderTransform is ScaleTransform scale)
                    {
                        scale.ScaleX = 1.0;
                        scale.ScaleY = 1.0;
                    }
                    ForceWindowToTop();
                    
                    // 【鼠标控制】动画完成后再次确认鼠标已释放（确保万无一失）
                    try
                    {
                        if (!MouseControlService.Instance.IsMouseReleased)
                        {
                            MouseControlService.Instance.ReleaseMouse();
                            System.Diagnostics.Debug.WriteLine("[ShowWindow] 动画后再次释放鼠标控制");
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"[ShowWindow] 动画后释放鼠标失败: {ex.Message}");
                    }
                }), DispatcherPriority.Background);
            }, config);
        }

        private void ShowWindowWithAnimationSync()
        {
            // 同步版本 - 保持兼容性
            Task.Run(async () => await ShowWindowWithAnimationAsync());
        }

        private async Task ShowWindowWithAnimationAsync()
        {
            await AnimationService.Instance.ShowWindowWithScaleAsync(this, () =>
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    ForceWindowToTop();
                }), DispatcherPriority.Background);
            });
        }
        
        private void ForceWindowToTop()
        {
            try
            {
                // 使用异步方式执行窗口操作，避免阻塞UI线程
                Task.Run(() =>
                {
                    try
                    {
                        // 在后台线程执行重量级操作
                        var helper = new WindowInteropHelper(this);
                        var hwnd = helper.Handle;
                        
                        if (hwnd != IntPtr.Zero)
                        {
                            // 简化的窗口置顶逻辑，避免线程附加操作
                            
                            // 1. 优先使用轻量级的SetWindowPos
                            bool success = NativeMethods.SetWindowPos(
                                hwnd,
                                NativeMethods.HWND_TOPMOST,
                                0, 0, 0, 0,
                                NativeMethods.SWP_NOMOVE | NativeMethods.SWP_NOSIZE | NativeMethods.SWP_NOACTIVATE
                            );
                            
                            if (success)
                            {
                                // 如果轻量级操作成功，回到UI线程激活窗口
                                Dispatcher.BeginInvoke(new Action(() =>
                                {
                                    try
                                    {
                                        this.Activate();
                                        System.Diagnostics.Debug.WriteLine("窗口已轻量级置顶");
                                    }
                                    catch (Exception ex)
                                    {
                                        System.Diagnostics.Debug.WriteLine($"窗口激活失败: {ex.Message}");
                                    }
                                }), DispatcherPriority.Background);
                            }
                            else
                            {
                                // 如果轻量级方法失败，使用备用方案（但仍然避免线程附加）
                                try
                                {
                                    NativeMethods.ShowWindow(hwnd, NativeMethods.SW_RESTORE);
                                    Thread.Sleep(10); // 稍微延迟，让系统处理完成
                                    
                                    Dispatcher.BeginInvoke(new Action(() =>
                                    {
                                        try
                                        {
                                            this.Topmost = true;
                                            this.Activate();
                                            System.Diagnostics.Debug.WriteLine("窗口已备用方式置顶");
                                        }
                                        catch (Exception ex)
                                        {
                                            System.Diagnostics.Debug.WriteLine($"备用置顶失败: {ex.Message}");
                                        }
                                    }), DispatcherPriority.Background);
                                }
                                catch (Exception ex)
                                {
                                    System.Diagnostics.Debug.WriteLine($"备用置顶方案失败: {ex.Message}");
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"异步窗口置顶失败: {ex.Message}");
                    }
                });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"窗口置顶初始化失败: {ex.Message}");
                // 如果异步方法失败，使用最简单的方式
                try
                {
                    this.Topmost = true;
                    this.Activate();
                }
                catch { }
            }
        }

        private async void HideWindowWithAnimation()
        {
            // 【鼠标控制】在隐藏窗口前开始恢复鼠标控制
            System.Diagnostics.Debug.WriteLine("[HideWindow] 准备恢复游戏的鼠标控制");
            
            // 使用企业级动画服务 - 创建丝滑的隐藏效果
            var config = AnimationConfig.Subtle.Clone();
            config.ScaleFrom = 1.0;
            config.ScaleHideTo = 1.0;  // 移除缩放效果，保持原始大小
            config.OpacityTo = 0.0;
            config.HideDuration = 220;
            config.EnableShadow = false;
            
            await AnimationService.Instance.HideWindowWithScaleAsync(this, () =>
            {
                // 动画完成后的处理
                Task.Run(() =>
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        // 重置缩放状态，确保下次显示时从正确的大小开始
                        if (this.RenderTransform is ScaleTransform scale)
                        {
                            scale.ScaleX = 1.0;
                            scale.ScaleY = 1.0;
                        }
                        // 确保窗口仍然在任务栏中，以便接收热键消息
                        this.ShowInTaskbar = true;
                        System.Diagnostics.Debug.WriteLine("窗口已隐藏，保持热键监听");
                        
                        // 【鼠标控制】窗口隐藏后，恢复游戏的鼠标控制
                        try
                        {
                            MouseControlService.Instance.RestoreMouse();
                            System.Diagnostics.Debug.WriteLine("[HideWindow] 鼠标控制已恢复给游戏");
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine($"[HideWindow] 恢复鼠标控制失败: {ex.Message}");
                        }
                        
                        // 【焦点管理】将焦点返回给游戏窗口
                        try
                        {
                            if (_previousForegroundWindow != IntPtr.Zero)
                            {
                                System.Diagnostics.Debug.WriteLine($"[HideWindow] 正在将焦点返回给游戏窗口: {_previousForegroundWindow}");
                                
                                // 使用多种方法确保焦点返回成功
                                NativeMethods.SetForegroundWindow(_previousForegroundWindow);
                                NativeMethods.BringWindowToTop(_previousForegroundWindow);
                                NativeMethods.ShowWindow(_previousForegroundWindow, NativeMethods.SW_SHOW);
                                
                                System.Diagnostics.Debug.WriteLine("[HideWindow] ✓ 焦点已返回给游戏窗口，用户无需再点击");
                            }
                            else
                            {
                                System.Diagnostics.Debug.WriteLine("[HideWindow] ⚠ 未保存游戏窗口句柄，无法返回焦点");
                            }
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine($"[HideWindow] 返回焦点失败: {ex.Message}");
                        }
                    }), DispatcherPriority.Background);
                });
            }, config);
        }

        private void HideWindowWithAnimationSync()
        {
            // 同步版本 - 保持兼容性
            Task.Run(async () => await HideWindowWithAnimationAsync());
        }

        private async Task HideWindowWithAnimationAsync()
        {
            await AnimationService.Instance.HideWindowWithScaleAsync(this, () =>
            {
                Task.Run(() =>
                {
                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        this.ShowInTaskbar = true;
                        System.Diagnostics.Debug.WriteLine("窗口已隐藏，保持热键监听");
                    }), DispatcherPriority.Background);
                });
            });
        }


        private void CloseApplication()
        {
            var animation = new DoubleAnimation
            {
                To = 0,
                Duration = TimeSpan.FromMilliseconds(200),
                EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut }
            };
            
            animation.Completed += (s, e) =>
            {
                Application.Current.Shutdown();
            };
            
            this.BeginAnimation(OpacityProperty, animation);
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            // 停止定时器
            if (_topmostTimer != null)
            {
                _topmostTimer.Stop();
                _topmostTimer = null;
            }
            
            // 注销热键
            UnregisterHotKey();
            
            // 取消默认关闭行为，使用自定义动画
            e.Cancel = true;
            CloseApplication();
        }
    }

    // MainWindow 的扩展成员：标题显示热键
    public partial class MainWindow
    {
        private void UpdateWindowTitleWithHotkey()
        {
            try
            {
                var hotkeyText = _hotkeySettings?.HotkeyText ?? "Ctrl+F8";
                var audioHotkeyText = _hotkeySettings?.AudioHotkeyText ?? "Ctrl+F9";
                this.Title = $"码枪堂 — 热键：{hotkeyText}(显示/隐藏) | {audioHotkeyText}(播放音效)";
                
                // 同步更新界面标题栏中的热键提示
                if (HotkeyHintText != null)
                {
                    HotkeyHintText.Text = $"热键：{hotkeyText}(显示/隐藏) | {audioHotkeyText}(播放音效)";
                }
            }
            catch
            {
                // 忽略标题更新异常，避免影响主流程
            }
        }
    }

    // 热键管理类
    public static class HotkeyManager
    {
        public const int WM_HOTKEY = 0x0312;

        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
    }
    
    // 低级键盘钩子管理类（用于在全屏游戏中捕获热键）
    public static class LowLevelKeyboardHook
    {
        private const int WH_KEYBOARD_LL = 13;
        private const int WM_KEYDOWN = 0x0100;
        private const int WM_KEYUP = 0x0101;
        private const int WM_SYSKEYDOWN = 0x0104;
        private const int WM_SYSKEYUP = 0x0105;
        
        private static IntPtr _hookId = IntPtr.Zero;
        private static LowLevelKeyboardProc? _proc;
        private static Action? _onHotkeyPressed;
        private static HotkeySettings? _hotkeySettings;
        
        public delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
        
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
        
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);
        
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
        
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string? lpModuleName);
        
        [StructLayout(LayoutKind.Sequential)]
        private struct KBDLLHOOKSTRUCT
        {
            public uint vkCode;
            public uint scanCode;
            public uint flags;
            public uint time;
            public IntPtr dwExtraInfo;
        }
        
        public static bool InstallHook(HotkeySettings hotkeySettings, Action onHotkeyPressed)
        {
            if (_hookId != IntPtr.Zero)
            {
                UninstallHook();
            }
            
            _hotkeySettings = hotkeySettings;
            _onHotkeyPressed = onHotkeyPressed;
            _proc = HookCallback;
            
            using (var curProcess = System.Diagnostics.Process.GetCurrentProcess())
            using (var curModule = curProcess.MainModule)
            {
                if (curModule != null)
                {
                    _hookId = SetWindowsHookEx(WH_KEYBOARD_LL, _proc,
                        GetModuleHandle(curModule.ModuleName), 0);
                }
            }
            
            return _hookId != IntPtr.Zero;
        }
        
        public static void UninstallHook()
        {
            if (_hookId != IntPtr.Zero)
            {
                UnhookWindowsHookEx(_hookId);
                _hookId = IntPtr.Zero;
            }
            _proc = null;
            _onHotkeyPressed = null;
            _hotkeySettings = null;
        }
        
        [DllImport("user32.dll")]
        private static extern short GetKeyState(int nVirtKey);
        private const int VK_CONTROL = 0x11;

        private const int VK_SHIFT = 0x10;
        private const int VK_ALT = 0x12;
        private const int VK_LWIN = 0x5B;
        private const int VK_RWIN = 0x5C;

        private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0 && _hotkeySettings != null)
            {
                // 检查是否是配置的热键
                if (wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_SYSKEYDOWN)
                {
                    var hookStruct = Marshal.PtrToStructure<KBDLLHOOKSTRUCT>(lParam);
                    
                    // 检查主键是否匹配
                    if (hookStruct.vkCode == _hotkeySettings.VirtualKeyCode)
                    {
                        // 检查修饰键是否匹配
                        bool ctrlDown = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
                        bool altDown = (GetKeyState(VK_ALT) & 0x8000) != 0;
                        bool shiftDown = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
                        bool winDown = ((GetKeyState(VK_LWIN) & 0x8000) != 0) || ((GetKeyState(VK_RWIN) & 0x8000) != 0);
                        
                        bool modifiersMatch = true;
                        if (_hotkeySettings.Modifiers.HasFlag(ModifierKeys.Control) != ctrlDown)
                            modifiersMatch = false;
                        if (_hotkeySettings.Modifiers.HasFlag(ModifierKeys.Alt) != altDown)
                            modifiersMatch = false;
                        if (_hotkeySettings.Modifiers.HasFlag(ModifierKeys.Shift) != shiftDown)
                            modifiersMatch = false;
                        if (_hotkeySettings.Modifiers.HasFlag(ModifierKeys.Windows) != winDown)
                            modifiersMatch = false;
                        
                        if (modifiersMatch)
                        {
                            // 调用回调函数（异步执行，不阻塞钩子）
                            try
                            {
                                _onHotkeyPressed?.Invoke();
                            }
                            catch
                            {
                                // 忽略回调中的异常，避免影响钩子
                            }
                        }
                    }
                }
            }
            
            return CallNextHookEx(_hookId, nCode, wParam, lParam);
        }
    }

    // 窗口助手类，用于实现点击穿透
    public static class WindowHelper
    {
        public static readonly DependencyProperty ClickThroughProperty =
            DependencyProperty.RegisterAttached("ClickThrough", typeof(bool), typeof(WindowHelper),
                new PropertyMetadata(false, OnClickThroughChanged));

        public static void SetClickThrough(Window element, bool value)
        {
            element.SetValue(ClickThroughProperty, value);
        }

        public static bool GetClickThrough(Window element)
        {
            return (bool)element.GetValue(ClickThroughProperty);
        }

        private static void OnClickThroughChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is Window window && (bool)e.NewValue)
            {
                // 设置窗口样式允许点击穿透
                var helper = new System.Windows.Interop.WindowInteropHelper(window);
                var exStyle = NativeMethods.GetWindowLong(helper.Handle, NativeMethods.GWL_EXSTYLE);
                exStyle |= NativeMethods.WS_EX_TRANSPARENT | NativeMethods.WS_EX_LAYERED;
                NativeMethods.SetWindowLong(helper.Handle, NativeMethods.GWL_EXSTYLE, exStyle);
            }
        }
    }

    // Native方法封装
    internal static class NativeMethods
    {
        public const int GWL_EXSTYLE = -20;
        public const int WS_EX_TRANSPARENT = 0x00000020;
        public const int WS_EX_LAYERED = 0x00080000;
        public const int WS_EX_TOPMOST = 0x00000008;
        public const int WS_EX_NOACTIVATE = 0x08000000;
        
        // 窗口位置标志
        public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
        public const uint SWP_NOMOVE = 0x0002;
        public const uint SWP_NOSIZE = 0x0001;
        public const uint SWP_SHOWWINDOW = 0x0040;
        public const uint SWP_NOACTIVATE = 0x0010;

        [DllImport("user32.dll")]
        public static extern int GetWindowLong(IntPtr hWnd, int nIndex);

        [DllImport("user32.dll")]
        public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
        
        [DllImport("user32.dll")]
        public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
        
        [DllImport("user32.dll")]
        public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
        
        [DllImport("user32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);
        
        [DllImport("user32.dll")]
        public static extern bool BringWindowToTop(IntPtr hWnd);
        
        [DllImport("user32.dll")]
        public static extern IntPtr GetForegroundWindow();
        
        [DllImport("user32.dll")]
        public static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
        
        [DllImport("kernel32.dll")]
        public static extern uint GetCurrentThreadId();
        
        [DllImport("user32.dll")]
        public static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);
        
        public const int SW_SHOW = 5;
        public const int SW_RESTORE = 9;
    }
}